<template>
  <el-row class="wrap">
    <el-col :span="24" class="warp-breadcrum">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>文件共享</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
    <el-col :span="24" class="wrap-main">
      <el-form size="small" :inline="true">
        <el-form-item>
          <el-input placeholder="请输入内容" v-model="getListName">
            <el-button slot="append" icon="el-icon-search" @click="getList(getListName)"></el-button>
          </el-input>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary">查询</el-button>
        </el-form-item> -->
        <el-form-item>
          <el-upload :before-upload="beforeUpload" :action="uploadUrl" :data="uploadData" :headers="uploadHeaders"
            :on-success="onSuccess">
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-table :data="fileRows" border size="small">
        <el-table-column label="文件名" prop="fileName"></el-table-column>
        <el-table-column label="类型" prop="type">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type === 1">图片</el-tag>
            <el-tag v-if="scope.row.type === 2">PDF</el-tag>
            <el-tag v-if="scope.row.type === 3">zip</el-tag>
            <el-tag v-if="scope.row.type === 4">其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="路径" prop="url"></el-table-column>
        <el-table-column label="创建日期" prop="createDate"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="downloadFile(scope.row.id, scope.row.fileName)" size="mini" type="button">下载</el-button>
            <el-button @click="removeFile(scope.row.id)" size="mini" type="danger">删除</el-button>
             <!-- 添加上链按钮
            <el-button @click="upChain(scope.row)" size="mini" type="primary" >上链</el-button> -->
            <el-button @click="queryChain(scope.row)" size="mini" type="success">查链</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination layout="total,prev, pager, next" @current-change="search" :page-size="limit" :total="total"
        style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 查链弹窗 -->
    <el-dialog title="查链结果展示" :visible.sync="dialogVisible" width="50%" center :before-close="handleClose">
      <el-table :data="gridData">
        <el-table-column property="name" label="文件名" width="200"></el-table-column>
        <el-table-column property="size" label="文件大小" width="200"></el-table-column>
        <el-table-column property="uptime" label="上链时间"></el-table-column>
        <el-table-column property="owner" label="上传用户"></el-table-column>

      </el-table>
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>

  </el-row>
</template>

<script>
import API from '../../api/api_file'
import API1 from '../../api/api_chain'

export default {
  name: "List",
  data() {
    return {
      gridData: [{
        name: '',
        size: '',
        uptime: '',
        owner: ''
      }],
      limit: 10,
      page: 1,
      total: 0,
      fileRows: [],
      uploadUrl: '',
      uploadData: {},
      uploadHeaders: { Authorization: '' },
      getListName: '',
      str: "",
      file: {},
      chain: {},
      // 弹窗设置
      dialogVisible: false,
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.gridData.splice(this.index)
        })
        .catch(_ => { });
    },
    search: function (val) {
      let that = this
      let params = {
        limit: that.limit,
        page: val
      }
      this.page = val
      API.files(params).then(res => {
        if (res.code === 0) {
          that.fileRows = res.page.rows
          that.total = res.page.total
        }
      })
    },

    getList: function () {
      let that = this
      API.getToken().then(res => {
        let token = res.token
        API.getList({ name: this.getListName, token: token }).then(res => {
          that.fileRows = res.page.rows
          that.total = res.page.total
        })
      })
    },
    beforeUpload: function () {
      let that = this
      return new Promise((resolve, reject) => {
        API.getToken().then(res => {
          let token = res.token
          let key = res.key
          that.uploadData = { token: token, key: key }
          that.uploadHeaders.Authorization = token
          that.uploadUrl = res.url
          resolve(true)
        })
        return {
          msg: '进入debug'
        }
      }).catch(err => {
        console.log(err)
        reject(false)
      })
    },
    removeFile: function (id) {
      let that = this
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return API.remove({ id: id }).then(res => {
          if (res.code === 0) {
            that.$message.success(res.msg)
            that.search(this.page);
          }
        })
      })
    },
    downloadFile: function (id, nane) {
      console.log('这是name', nane)
      API.getToken().then(res => {
        let token = res.token
        console.log('这是权限', res)
        API.downLoad({ id: id, token: token }).then(res => {
          console.log('这是下载', res)
          if (res.status === 200) {
            console.log("下载成功")
            this.exportFile(res.data, nane)
            that.$message.success('成功')
          } else {
            console.log("下载失败")
          }
        });

      })

    },
    //文件下载
    exportFile: function (data, name) {

      // let url = window.URL.createObjectURL(new Blob([file]));

      // let link = document.createElement('a');

      // link.style.display = 'none';

      // link.href = url;

      // link.setAttribute('download', name);

      // document.body.appendChild(link);

      // link.click();

      // document.body.removeChild(link); // 下载完成移除元素

      // window.URL.revokeObjectURL(url); // 释放掉blob对象
      try {
        // const blobUrl = window.URL.createObjectURL(new Blob([data]), { type: 'multipart/form-data;charset=UTF-8;image/png' })
        const blobUrl = window.URL.createObjectURL(data)
        const a = document.createElement('a')
        a.style.display = 'none'
        a.download = name
        a.href = blobUrl
        a.click()

      } catch (e) {
        alert('保存文件出错')
      }
    },

    //上链函数
      upChain: function (file) {
        console.log(file);  

        let params = {          
          key: file.fileName,
          name : file.fileName,
          size : file.size,
          uptime : file.createDate,
          owner : file.uploader,
          operation : "上链"  
        }
        console.log(params.chain)
        console.log(params.token)
        return API1.upChain(params).then(res =>{ 
          if(res.code === 200){
            console.log(res)
            
            this.$message.success(res.data)
          }
        }) 
      },


    //查链函数
    queryChain: function (file) {
      let params = {
        key: file.fileName,
      }

      API1.query(params).then(res => {
        res = res.msg
        console.log(res)
        const newline = {
          name: res.name,
          size: res.size,
          uptime: res.uptime,
          owner: res.owner,
        }
        this.index++
        this.gridData.push(newline)
        this.dialogVisible = true
      })
        .catch(error => {
          console.log(error)
        })

    },

    onSuccess: function () {
      this.search(this.page)
    },
  },
  mounted() {
    this.search(1);
  }
}
</script>

<style scoped>
</style>
